package com.xdap.keymen.service.punch;

import com.definesys.mpaas.query.MpaasQuery;
import com.google.gson.*;
import com.xdap.keymen.entity.PunchSalesSupportTicketEntity;
import com.xdap.motor.entity.SnowflakeIdWorker;
import com.xdap.motor.vo.ResponseVo;
import com.xdap.runtime.service.RuntimeAppContextService;
import com.xdap.runtime.service.RuntimeDatasourceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Service;


import java.util.*;

@Service
@RequiredArgsConstructor
@Slf4j
public class PunchSalesSupportTicketService {
    private final RuntimeDatasourceService runtimeDatasourceService;
    private final RuntimeAppContextService runtimeAppContextService;
    private final SnowflakeIdWorker snowflakeIdWorker;


    public ResponseVo addSalesSupportTicket(Map<String, Object> params) {
        String event=params.get("event").toString();
        if(!event.equals("0")){
            return ResponseVo.error("不是新增");
        }
        PunchSalesSupportTicketEntity entity = new PunchSalesSupportTicketEntity();
        List<HashMap<String,String>> customFiledList = (ArrayList<HashMap<String,String>>) params.get("customFiledList");
        entity.setId(snowflakeIdWorker.nextId());
        entity.setDocumentId(snowflakeIdWorker.nextId());
        entity.setTicketId(params.get("sheetId").toString());
        entity.setStaffId(((HashMap<String,Object>)params.get("toStaff")).get("id").toString());
        entity.setContactName(getJsonValue(customFiledList, "联系人姓名"));
        entity.setRemarks(getJsonValue(customFiledList, "备注"));
        entity.setProcessingResult(getJsonValue(customFiledList, "处理结果"));
        //entity.setAttachmentOrImages();
        entity.setProblemDescription(getJsonValue(customFiledList, "问题描述"));
        entity.setSalesOrderLineNumber(getJsonValue(customFiledList, "工单行号"));
        entity.setContactInformation(getJsonValue(customFiledList, "联系方式"));
        entity.setSalesOrderNumber(getJsonValue(customFiledList, "订单编号"));
        entity.setSupportTicketNumber(getNo());
        entity.setSupportTicketType(getJsonValue(customFiledList, "工单类型"));
        entity.setClientName(getJsonValue(customFiledList, "客户名称"));
        entity.setPunchId(getJsonValue(customFiledList, "盘起码"));
        entity.setAttachments(getAttachments((List<String>)params.get("attachList")));
        entity.setCustomerFile(getCustomerFile(getJsonValue(customFiledList, "上传附件")));

        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.doInsert(entity);

        return null;
    }

    private String getJsonValue(List<HashMap<String,String>> list, String key) {
        for (HashMap<String,String> element : list) {
            //JsonObject jsonObject = element.getAsJsonObject();
            // 判断是否包含"aaa"这个key
            if (element.get("key").toString().equals(key)) {
                // 取出对应的value并添加到结果列表
                return  element.get("value").toString();
            }
        }
        return "";
    }

    private String getCustomerFile(String jstr) {
        Gson gson = new GsonBuilder().setFieldNamingStrategy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
        jstr=jstr.replace("&quot;","\"");
        JsonArray jsonArray = gson.fromJson(jstr, JsonArray.class);
        String attachments = "";
        for (JsonElement jsonElement : jsonArray) {
            JsonObject jsonObject = jsonElement.getAsJsonObject();
            String url = jsonObject.get("url").getAsString();
            attachments = attachments.concat("<p><a href=\"").concat(url).concat("\">附件</a></p>");
        }

        return   attachments;
    }

    private String getAttachments(List<String> list) {
        String attachments = "";
        for (String element : list) {
            attachments = attachments.concat("<p><a href=\"").concat(element).concat("\">附件</a></p>");
        }
        return   attachments;
    }

    private String getNo() {
        String nowDate = DateFormatUtils.format(new Date(), "yyyyMMdd");
        String storeNo = "";
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.sql("select ifnull(max(right(support_ticket_number,4))+1,1) as no from punch_sales_support_ticket where left(support_ticket_number,8)='"+nowDate+"'");
        Integer no = query.doQueryFirst(Integer.class);
        storeNo=nowDate.concat(String.format("%04d", no));
        return storeNo;
    }

    public PunchSalesSupportTicketEntity getSalesSupportTicket(String id) {
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.eq("id",id);
        return query.doQueryFirst(PunchSalesSupportTicketEntity.class);
    }
}
